﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

using DotNetNuke.Entities.Tabs;
using iFinity.DNN.Modules.UrlMaster;
using iFinity.DNN.Modules.UrlMaster.Entities;

namespace iFinity.DNN.Modules.BlogFriendlyUrlProvider.UI
{
    /// <summary>
    /// This is the code-behind for the Settings.ascx control.  This inherits from the standard .NET UserControl, but also implements the ModuleProvider specific IProviderSettings.
    /// This control will be loaded by the Portal Urls page.  It is optional for module providers, but allows users to control module settings via the interface, rather than 
    /// having to set options via web.config settings.  The writing / reading of the items from the configuration file is handled by the Url Master module, and doesn't need to 
    /// be implemented.
    /// </summary>
    public partial class Settings : System.Web.UI.UserControl, IProviderSettings
    {
        private int _portalId;
        #region controls
        protected Label lblHeader;
        protected DropDownList ddlBlogTitle;
        protected DropDownList ddlBlogPostStyle;
        protected TextBox txtTagPath;
        protected TextBox txtPostPath;
        protected TextBox txtCatPath;
        protected TextBox txtDatePath;
        protected DropDownList ddlNoDnnPagePathTab;
        protected CheckBox chkReturn404ForMissingEntries;
        protected TextBox txtStartingEntryId;
        protected TextBox txtReplaceChars;
        protected CheckBox chkReplaceDoubleSpaces;
        #endregion
        #region Web Form Designer Generated Code
        //[System.Diagnostics.DebuggerStepThrough]
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion
        #region events code
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //note page load runs after LoadSettings(); because of dynamic control loading
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        #endregion
        #region content methods
        private void LocalizeControls()
        {
            //build the list of blog titles
            ddlBlogTitle.Items.Clear();
            foreach (BlogModuleProvider.BlogTitleOptions blogTitleOption in Enum.GetValues(typeof(BlogModuleProvider.BlogTitleOptions)))
            {
                ddlBlogTitle.Items.Add(new ListItem(blogTitleOption.ToString().Replace("_", " "), blogTitleOption.ToString()));
            }
            lblHeader.Text = DotNetNuke.Services.Localization.Localization.GetString("Header.Text");
            ddlBlogPostStyle.Items.Clear();
            foreach (
                BlogModuleProvider.BlogPostUrlOptions blogPostUrlOption in
                    Enum.GetValues(typeof (BlogModuleProvider.BlogPostUrlOptions)))
            {
                ddlBlogPostStyle.Items.Add(new ListItem(blogPostUrlOption.ToString().Replace("_", " "), blogPostUrlOption.ToString()));
            }

            //only publicly available non-admin or host tabs are used.
            TabController tc = new TabController();
            //load tabs into drop down list            
            TabCollection tabs = tc.GetTabsByPortal(_portalId);
            //loop through the tabs and add the ones that aren't admin or host tabs
            ddlNoDnnPagePathTab.Items.Clear();
            string firstItem = DotNetNuke.Services.Localization.Localization.GetString("NoTabSelected.Text", this.LocalResourceFile);
            ddlNoDnnPagePathTab.Items.Add(new ListItem(firstItem, "-1"));
            foreach (TabInfo tab in tabs.Values)
            {
                if (tab.IsSuperTab == false)//TODO: filter admin tabs as well?
                    ddlNoDnnPagePathTab.Items.Add(new ListItem(tab.TabName, tab.TabID.ToString()));
            }
            
        }
        #endregion
        #region IProviderSettings Members
        /// <summary>
        /// LoadSettings is called when the module control is first loaded onto the page
        /// </summary>
        /// <remarks>
        /// This method shoudl read all the custom properties of the provider and set the controls
        /// of the page to reflect the current settings of the provider.
        /// </remarks>
        /// <param name="provider"></param>
        public void LoadSettings(ModuleFriendlyUrlProvider provider)
        {
            //build list of controls
            if (!IsPostBack)
                LocalizeControls();
            //take all the values from the provider and show on page
            //check type safety before cast
            if (provider.GetType() == typeof(BlogModuleProvider))
            {
                BlogModuleProvider blogProvider = (BlogModuleProvider)provider;
                txtTagPath.Text = blogProvider.TagPath;
                txtPostPath.Text = blogProvider.PostPath;
                txtCatPath.Text = blogProvider.CatPath;
                txtDatePath.Text = blogProvider.DatePath;
                ddlBlogTitle.SelectedValue = blogProvider.BlogTitle.ToString();
                ddlBlogPostStyle.SelectedValue = blogProvider.BlogPostUrlStyle.ToString();

                if (blogProvider.StartingEntryId > 0)
                    txtStartingEntryId.Text = blogProvider.StartingEntryId.ToString();
                else
                    txtStartingEntryId.Text = "";

                string selTabId = blogProvider.NoDnnPagePathTabId.ToString();
                ddlNoDnnPagePathTab.SelectedValue = selTabId;
                if (ddlNoDnnPagePathTab.SelectedIndex == -1)//not found
                {
                    ddlNoDnnPagePathTab.SelectedIndex = 0;//first item
                }

                chkReturn404ForMissingEntries.Checked = blogProvider.Return404ForMissingEntries;
                //922 : replacement chars
                //but only if supported by the underlying version of Url Master
                FriendlyUrlOptions options = new FriendlyUrlOptions();
                if (options.GetType().GetMember("ReplaceChars") != null)
                {
                    txtReplaceChars.Text = blogProvider.ReplaceChars;
                    chkReplaceDoubleSpaces.Checked = blogProvider.ReplaceDoubleSpaces;
                }
                else
                {
                    System.Web.UI.HtmlControls.HtmlTableRow trReplaceChars = (System.Web.UI.HtmlControls.HtmlTableRow)this.FindControl("trReplaceChars");
                    if (trReplaceChars != null)
                        trReplaceChars.Visible = false;

                    System.Web.UI.HtmlControls.HtmlTableRow trReplaceDoubleSpaces = (System.Web.UI.HtmlControls.HtmlTableRow)this.FindControl("trReplaceDoubleSpaces");
                    if (trReplaceDoubleSpaces != null)
                        trReplaceDoubleSpaces.Visible = false;

                }
            }
        }
        /// <summary>
        /// UpdateSettings is called when the 'update' button is clicked on the interface.
        /// This should take any values from the page, and set the individual properties on the 
        /// instance of the module provider.
        /// </summary>
        /// <param name="provider"></param>
        public void UpdateSettings(ModuleFriendlyUrlProvider provider)
        {
            //check type safety before cast
            if (provider.GetType() == typeof(BlogModuleProvider))
            {
                //take values from the page and set values on provider    
                BlogModuleProvider blogProvider = (BlogModuleProvider)provider;
                blogProvider.TagPath = txtTagPath.Text;
                blogProvider.PostPath = txtPostPath.Text;
                blogProvider.DatePath = txtDatePath.Text;
                blogProvider.CatPath = txtCatPath.Text;
                blogProvider.BlogTitle = blogProvider.ConvertBlogTitleOptionsFromString(ddlBlogTitle.SelectedValue);
                blogProvider.BlogPostUrlStyle = blogProvider.ConvertUrlOptionsFromString(ddlBlogPostStyle.SelectedValue);

                FriendlyUrlOptions options = new FriendlyUrlOptions();
                if (options.GetType().GetMember("ReplaceChars") != null)
                {
                    //uses reflection to ensure these options are supported before saving them
                    blogProvider.ReplaceChars = txtReplaceChars.Text;
                    blogProvider.ReplaceDoubleSpaces = chkReplaceDoubleSpaces.Checked;
                }

                string rawStartingEntryId = txtStartingEntryId.Text;
                int startingEntryId = 0;
                if (int.TryParse(rawStartingEntryId, out startingEntryId))
                    blogProvider.StartingEntryId = startingEntryId;

                string rawTabId = ddlNoDnnPagePathTab.SelectedValue;
                int selTabId;
                if (int.TryParse(rawTabId, out selTabId))
                {
                    if (selTabId > 0)
                        blogProvider.NoDnnPagePathTabId = selTabId;
                    else
                        blogProvider.NoDnnPagePathTabId = 0;
                }
                blogProvider.Return404ForMissingEntries = chkReturn404ForMissingEntries.Checked;
            }

        }
        
        public System.Web.UI.Control Control
        {
            get { return this;  }
        }

        public string ControlPath
        {
            get { return base.TemplateSourceDirectory; }
        }

        public string ControlName
        {
            get { return "ProviderSettings";  }
        }

        public string LocalResourceFile
        {
            get { return "DesktopModules/iFinity.BlogFriendlyUrlProvider/App_LocalResources/Settings.ascx.resx"; }
        }
        public int PortalId
        {
            get { return _portalId; }
            set { _portalId = value; }
        }

        #endregion

    }
}
